package com.cz.service;

import java.util.List;
import java.util.UUID;

import javax.validation.Valid;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.glassfish.grizzly.http.server.Request;

import com.cz.bean.User;
import com.cz.dao.UserMapper;
import com.cz.util.DbUtil;
import com.cz.util.MD5;
import com.google.common.base.Strings;

/**
 * Created by Administrator on 2014/12/24.
 */
@Path("u")
public class UserResource {
    static Logger logger = Logger.getLogger(UserResource.class);
    SqlSession sqlSession = DbUtil.getSessionFactory().openSession();
    UserMapper dao = sqlSession.getMapper(UserMapper.class);

    public UserResource() {
        logger.debug("new User Resource");
    }

    @Context Request request;

    @Path("/{id}")
    @GET
    @Produces(MediaType.APPLICATION_JSON) // @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public User getById(@PathParam("id") String id) {
        User user = null;

        try {
            user = dao.getById(id);
        } catch (Exception e) {
            logger.error("user getbyid failed: ", e);
        } finally {
            sqlSession.close();
        }

        return user;
    }

    @Path("/o/{id}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public User getByOther(@PathParam("id") String id) {
        User user = null;
        try {
            user = dao.getByOther(id);
        } catch (Exception e)
        {
            logger.error("user getByOther failed: ", e);
        } finally {
            sqlSession.close();
        }
        return user;
    }

    @Path("/login/{id}/{pwd}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public User login(@PathParam("id") String id, @PathParam("pwd") String pwd) {
        User user = null;
        try {
            user = dao.getByOther(id);
            if (user != null && !Strings.isNullOrEmpty(user.getPassword()))
            {
                if ( !user.getPassword().equalsIgnoreCase(MD5.hex(pwd)))
                    user = null; // password error
            }
        }catch (Exception e)
        {
            logger.error("user login failed: ", e);
        } finally {
            sqlSession.close();
        }

        return user;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public String add(@Valid User user) {
//    	Request r = request;
        if (user == null) {
            return null;
        }

        user.setPassword(MD5.hex(user.getPassword()));
        UUID uid = UUID.randomUUID();
        user.setId(uid.toString());

        String id = null;

        try {
            dao.add(user);
            sqlSession.commit();
            id = user.getId();
        } catch (Exception e) {
            sqlSession.rollback();
            logger.error("user add failed: ", e);
        } finally {
            sqlSession.close();
        }

        return id;
    }

    @PUT
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public boolean update(User user) {
        boolean ret = false;
        try
        {
            dao.update(user);
            sqlSession.commit();
            ret = true;
        } catch (Exception e)
        {
            sqlSession.rollback();
            logger.error("user update failed: ", e);
        } finally
        {
            sqlSession.close();
        }

        return ret;
    }

    @Path("/chpwd/{id}/{password}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public boolean changePassword(@PathParam("id") String id, @PathParam("password") String password) {
        boolean ret = false;
        try
        {
            dao.passwd(id, MD5.hex(password));
            sqlSession.commit();
            ret = true;
        } catch ( Exception e)
        {
            sqlSession.rollback();
            logger.error("user change passwd failed: ", e);
        } finally {
            sqlSession.close();
        }
        return ret;
    }

    @Path("/{id}")
    @DELETE
    @Produces(MediaType.APPLICATION_JSON)
    public boolean delete(@PathParam("id") String id) {
        boolean ret = false;
        try {
            dao.delete(id);
            sqlSession.commit();
            ret = true;
            logger.info("user delete ok: " + id);
        } catch (Exception e)
        {
            sqlSession.rollback();
            logger.error("user delete failed: ", e);
        } finally {
            sqlSession.close();
        }
        return ret;
    }
    @Path("/getByIds/{ids}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public List<User> getByIds(@PathParam("ids") String  ids) {
        List<User> us =null;
        try{
            us =  dao.getByIds(ids.split(","));
        } catch ( Exception e)
        {
            logger.error("User getByIds getRequireList failed: ", e);
        } finally {
            sqlSession.close();
        }
        return us;
    }

    @Path("/chnick/{nick}/{id}")
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public boolean checkNick(@PathParam("nick") String nick,@PathParam("id") String id) {
        User user = null;
        boolean ret = false;
        try {
            user = dao.checkNick(nick,id);
            if (user == null ){
                ret = true;
            }
        }catch (Exception e)
        {
            logger.error("user checkNick failed: ", e);
        } finally {
            sqlSession.close();
        }

        return ret;
    }
}
